package com.gitee.xhs.keyedState.reducingState;

import com.gitee.xhs.sampleRecod.transactionRecord.Transaction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.configuration.Configuration;

/**
 * @author BigHead
 * @date 2022/6/30 13:56
 * @description ReducingStateKeyedProcessFunction
 */
public class ReducingStateKeyedProcessFunction extends KeyedProcessFunction<Long, Transaction, String> {

    private transient ReducingState<Double> reducingState;

    @Override
    public void open(Configuration configuration) throws Exception {
        reducingState = getRuntimeContext().getReducingState(
                ReducingStateConstant.REDUCING_STATE_DESCRIPTOR
        );
    }

    @Override
    public void processElement(Transaction value, KeyedProcessFunction<Long, Transaction, String>.Context ctx, Collector<String> out) throws Exception {
        reducingState.add(value.getAmount());
        out.collect(value.toString());
    }
}
